package router

import (
	"log"
	"time"
)

// 放入消息到数据库
// 群组消息不需要核心维护
// 但是为了后期为了方便维护

func PutNoSendMsg(msg interface{}) {
	switch msg.(type) {
	case Single:
		single := msg.(Single)
		m, _ := single.Msg.MarshalJSON()
		_, err := DB.Exec("insert into nosend_message set mark=?,msg=?,create_time=?,status=0", "/single/"+single.To, m, time.Now().Unix())
		if err != nil {
			log.Panicln(err)
		}
	case Room:
		room := msg.(Room)
		_, err := DB.Exec("insert into nosend_message set mark=?,msg=?,create_time=?,status=0", "/room/"+room.Name, room.Message, time.Now().Unix())
		if err != nil {
			log.Panicln(err)
		}
	}
}

// change status
func _changeStatus(id int) {
	DB.Exec("update nosend_message set status=1 where id=?", id)
}

// 从数据库中获取消息
// 群组消息不需要核心维护
func GetNoSendMsg(uuid string) []*NosendMessage {
	rows, err := DB.Query("select id,mark,msg,create_time from nosend_message where mark=? and status=0", "/single/"+uuid)
	if err != nil {
		log.Panicln(err)
	}
	allSingle := make([]*NosendMessage, 0)
	single := &NosendMessage{}
	for rows.Next() {
		err := rows.Scan(&single.Id, &single.UUID, &single.Msg, &single.CreateTime)
		if err != nil {
			log.Panicln(err)
		}
		allSingle = append(allSingle, single)
		go _changeStatus(single.Id)
	}
	return allSingle
}
